import re
from lly.logconfig import logger
from lly.vim.command import cmd_result_path, execute_os_cmd, KEY_RETURNCODE, KEY_STD_OUT


def get_phone_ip():
    '''
    获取手机ip信息，

    步骤：
    1.根据 adb shell dumpsys connectivity 获取网络信息
    2.解析LinkAddresses: [fe80::da63:75ff:fe9f:37e6/64,192.168.1.104/24,] 类似字符串
        中的第二个字段
    '''
    cmd = "adb shell dumpsys connectivity"
    cmd_result = execute_os_cmd(cmd)
    result_code = cmd_result[KEY_RETURNCODE]
    if result_code == 0:
        connectivity = None
        with cmd_result_path(cmd_result[KEY_STD_OUT]).open(encoding='uft-8') as f:
            connectivity = f.read()
        if connectivity:
            ip_regx = r'LinkAddresses:\s*\[[^,\]]+?,(?P<ip>[\w.\d]*?)/\d+.*?\]'
            ip_re = re.compile(ip_regx, re.DOTALL)
            result = []
            for match in ip_re.finditer(connectivity):
                logger.info(match.group())
                result.append(match['ip'])
            if len(result) > 0:
                return result

    raise Exception(cmd_result)
